package com.zimmur.service.impl.account;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.zimmur.dao.account.IUserAddressDao;
import com.zimmur.model.account.UserAddress;
import com.zimmur.service.account.IUserAddressService;

@Service("userAddressService")
public class UserAddressServiceImpl implements IUserAddressService {

	@Resource
	private IUserAddressDao userAddressDao;
	
	@Override
	public UserAddress selectById(long addrId) {
		return userAddressDao.selectByPrimaryKey(addrId);
	}

	@Override
	public boolean insert(UserAddress address) {
		try{
			boolean bret = userAddressDao.insertSelective(address)>0?true:false;
			//默认地址处理
			if(address.getIsDefault()==1){
				setDefaultAddress(address.getUserId(), Long.parseLong(address.getAddressId()));
			}
			return bret;
		}catch(Exception er){
			
		}
		return false;
	}

	@Override
	public boolean update(UserAddress address) {
		try{
			boolean bret = userAddressDao.updateByPrimaryKeySelective(address)>0?true:false;
			//默认地址处理
			if(address.getIsDefault()==1){
				setDefaultAddress(address.getUserId(), Long.parseLong(address.getAddressId()));
			}
			return bret;
		}catch(Exception er){
			return false;
		}
	}

	@Override
	public List<UserAddress> selectByUserId(long userId) {
		return userAddressDao.selectByUserId(userId);
	}

	@Override
	public boolean setDefaultAddress(long userId, long addrId) {
		try{
			userAddressDao.updateResetDefault(userId);
			Map<String, Object> map = new HashMap<>();
			map.put("addressId", addrId);
			return userAddressDao.updateAddressDefault(map)>0?true:false;
		}catch(Exception e){
			
		}
		return false;
	}

	@Override
	public boolean delete(long addressId) {
		return userAddressDao.deleteByPrimaryKey(addressId)>0?true:false;
	}

}
